//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { Button, Card, Form, Input, message, Modal, Popover, Space, Table } from "antd";
import { useStores } from "@/hooks";
import type { GitRepoInfo } from "@/api/project_git";
import { add_git_repo, list_git_repo, update_git_repo, remove_git_repo } from "@/api/project_git";
import { request } from "@/utils/request";
import type { ColumnsType } from 'antd/lib/table';
import { open as shell_open } from '@tauri-apps/api/shell';
import { get_http_url, type LocalRepoInfo } from "@/api/local_repo";
import { openGitAssistant } from "@/utils/git_assistant";
import AddRepoModal from "@/pages/Workbench/components/localrepo/AddRepoModal";
import { MoreOutlined } from "@ant-design/icons";
import { set_link_info } from "@/api/project_tool";

interface EditGitRepoModalProps {
    repoInfo?: GitRepoInfo;
    onCancel: () => void;
    onOk: () => void;
}

const EditGitRepoModal = (props: EditGitRepoModalProps) => {
    const userStore = useStores('userStore');
    const projectStore = useStores('projectStore');

    const [name, setName] = useState(props.repoInfo?.basic_info.name ?? "");
    const [gitUrl, setGitUrl] = useState(props.repoInfo?.basic_info.git_url ?? "");

    const addGitRepo = async () => {
        await request(add_git_repo({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            basic_info: {
                name: name,
                git_url: gitUrl,
            },
        }));
        props.onOk();
    };

    const updateGitRepo = async () => {
        if (props.repoInfo == undefined) {
            return;
        }
        await request(update_git_repo({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            git_repo_id: props.repoInfo.git_repo_id,
            basic_info: {
                name: name,
                git_url: gitUrl,
            },
        }));
        props.onOk();
    };

    return (
        <Modal open title={`${props.repoInfo == undefined ? "增加" : "更新"}代码仓库`} mask={false}
            okText={props.repoInfo == undefined ? "增加" : "更新"} okButtonProps={{ disabled: name == "" || !(gitUrl.startsWith("https://") || gitUrl.startsWith("git@")) }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.repoInfo == undefined) {
                    addGitRepo();
                } else {
                    updateGitRepo();
                }
            }}>
            <Form labelCol={{ span: 3 }}>
                <Form.Item label="名称">
                    <Input value={name} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setName(e.target.value.trim());
                    }} />
                </Form.Item>
                <Form.Item label="克隆地址" help="地址必须是https://或者git@开头">
                    <Input value={gitUrl} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setGitUrl(e.target.value.trim());
                    }} />
                </Form.Item>
            </Form>
        </Modal>
    );
};

const GitRepoList = () => {
    const userStore = useStores('userStore');
    const projectStore = useStores('projectStore');
    const localRepoStore = useStores('localRepoStore');

    const [showAddModal, setShowAddModal] = useState(false);
    const [repoInfoList, setRepoInfoList] = useState<GitRepoInfo[]>([]);
    const [cloneRepoInfo, setCloneRepoInfo] = useState<GitRepoInfo | null>(null);
    const [updateRepoInfo, setUpdateRepoInfo] = useState<GitRepoInfo | null>(null);
    const [removeRepoInfo, setRemoveRepoInfo] = useState<GitRepoInfo | null>(null);
    const [vsInitRepoInfo, setVsInitRepoInfo] = useState<GitRepoInfo | null>(null);

    const loadRepoInfoList = async () => {
        const res = await request(list_git_repo({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
        }));
        setRepoInfoList(res.repo_info_list);
    };

    const findLocalRepo = (gitUrl: string): LocalRepoInfo | null => {
        for (const repo of localRepoStore.repoExtList) {
            for (const remote of repo.remoteList) {
                if (remote.url == gitUrl) {
                    return repo.repoInfo;
                }
            }
        }
        return null;
    };

    const removeRepo = async () => {
        if (removeRepoInfo == null) {
            return;
        }
        await request(remove_git_repo({
            session_id: userStore.sessionId,
            project_id: projectStore.curProjectId,
            git_repo_id: removeRepoInfo.git_repo_id,
        }));
        setRemoveRepoInfo(null);
        await loadRepoInfoList();
        message.info("删除成功");
    };

    const setGitHook = async () => {
        if (vsInitRepoInfo == null) {
            return;
        }
        const localRepo = findLocalRepo(vsInitRepoInfo.basic_info.git_url);
        if (localRepo == null) {
            return;
        }
        await set_link_info(localRepo.path, projectStore.curProjectId);
        setVsInitRepoInfo(null);
        message.info("设置成功");
    };

    const columns: ColumnsType<GitRepoInfo> = [
        {
            title: "名称",
            width: 100,
            dataIndex: ["basic_info", "name"],
        },
        {
            title: "克隆地址",
            render: (_, row: GitRepoInfo) => (
                <a onClick={e => {
                    e.stopPropagation();
                    e.preventDefault();
                    shell_open(get_http_url(row.basic_info.git_url));
                }}>{row.basic_info.git_url}</a>
            ),
        },
        {
            title: "操作",
            width: 90,
            render: (_, row: GitRepoInfo) => {
                const localRepo = findLocalRepo(row.basic_info.git_url);
                return (
                    <Space>
                        <div style={{ width: "80px" }}>
                            {localRepo == null && (
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    setCloneRepoInfo(row);
                                }}>克隆到本地</Button>
                            )}
                            {localRepo != null && (
                                <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    openGitAssistant(localRepo, userStore.userInfo.userName, userStore.userInfo.userType, userStore.userInfo.extraToken);
                                }}>查看本地仓库</Button>
                            )}
                        </div>
                        {projectStore.isAdmin && (
                            <Popover placement="bottom" trigger="click" content={
                                <Space direction="vertical">
                                    {localRepo != null && (
                                        <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setVsInitRepoInfo(row);
                                        }}>VsCode插件设置</Button>
                                    )}
                                    <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setUpdateRepoInfo(row);
                                    }} disabled={projectStore.isClosed}>修改</Button>
                                    <Button type="link" style={{ minWidth: 0, padding: "0px 0px" }} danger
                                        onClick={e => {
                                            e.stopPropagation();
                                            e.preventDefault();
                                            setRemoveRepoInfo(row);
                                        }} disabled={projectStore.isClosed}>删除</Button>
                                </Space>
                            }>
                                <MoreOutlined />
                            </Popover>
                        )}
                    </Space>
                );
            }
        }
    ];

    useEffect(() => {
        loadRepoInfoList();
    }, []);

    return (
        <Card title="代码仓库"
            headStyle={{ backgroundColor: "#eee", fontSize: "16px", fontWeight: 600 }} style={{ marginBottom: "10px" }}
            extra={
                <>
                    {projectStore.isAdmin && (
                        <Button type="primary" onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            setShowAddModal(true);
                        }} disabled={projectStore.isClosed}>增加</Button>
                    )}
                </>
            }>
            <Table rowKey="git_repo_id" dataSource={repoInfoList} columns={columns} pagination={false} />

            {showAddModal == true &&
                <EditGitRepoModal onCancel={() => setShowAddModal(false)}
                    onOk={() => {
                        setShowAddModal(false);
                        loadRepoInfoList();
                    }} />
            }
            {cloneRepoInfo != null && (
                <AddRepoModal name={cloneRepoInfo.basic_info.name} remoteUrl={cloneRepoInfo.basic_info.git_url}
                    onCancel={() => setCloneRepoInfo(null)}
                    onOk={() => {
                        const tmpList = repoInfoList.filter(item => item.git_repo_id != cloneRepoInfo.git_repo_id);
                        setRepoInfoList(tmpList);
                        setCloneRepoInfo(null);
                        localRepoStore.init().then(() => loadRepoInfoList());
                    }} />
            )}
            {updateRepoInfo != null && (
                <EditGitRepoModal repoInfo={updateRepoInfo} onCancel={() => setUpdateRepoInfo(null)}
                    onOk={() => {
                        const tmpList = repoInfoList.filter(item => item.git_repo_id != updateRepoInfo.git_repo_id);
                        setRepoInfoList(tmpList);
                        setUpdateRepoInfo(null);
                        loadRepoInfoList();
                    }} />
            )}
            {removeRepoInfo != null && (
                <Modal open title="删除代码仓库" mask={false}
                    okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemoveRepoInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        removeRepo();
                    }}>
                    是否删除代码仓库&nbsp;{removeRepoInfo.basic_info.name}&nbsp;?
                </Modal>
            )}
            {vsInitRepoInfo != null && (
                <Modal open title="VsCode插件设置" mask={false}
                    okText="设置"
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setVsInitRepoInfo(null);
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setGitHook();
                    }}>
                    安装和配置<a onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        shell_open("https://marketplace.visualstudio.com/items?itemName=linksaas.local-api");
                    }}>linksaas插件</a>后，可在VsCode里面查看任务/缺陷，支持代码评论功能。
                </Modal>
            )}
        </Card>
    );
};

export default observer(GitRepoList);